/**
 * 
 * Created by haua on 16/8/4.
 */

(function(){
    var debug=false,
        Geocoder,weather,stoped = false,
        HPosition = {
            position:null, //如果有gps信息则会存到此处
            cityInf:null, //如果有城市信息则会存到此处
            weather:null, //如果有天气信息则会存到此处
            def:{ //默认的信息，调试用
                position:{
                    lat:23.143082,
                    lng:113.338686
                },
                cityInf:{ //只有在本地调试时才用的默认数据
                    "adcode": "440104",
                    "city": "广州市",
                    "country": "中国",
                    "direction": "附近",
                    "distance": "9",
                    "district": "越秀区",
                    "province": "广东省",
                    "street": "七横路",
                    "street_number": "7号",
                    "country_code": 0
                },
                weather:{
                    adcode: "440100",
                    city: "广州市",
                    humidity: "73",
                    info: "OK",
                    province: "广东",
                    reportTime: "2015-07-16 11:00:00",
                    temperature: 31,
                    weather: "多云",
                    windDirection: "北",
                    windPower: 4
                }
            },
            userSel:{ //用户自主定义的信息
                position:null,
                cityInf:null,
                weather:null
            }
        },
        isLocal = location.hostname=='localhost';
    
    /**
     * 根据gps信息获取城市信息
     * "formatted_address":"广东省广州市天河区石牌街道芳草园",
     * "province":"广东省",
     * "city":"广州市",
     * "citycode":"020",
     * "district":"天河区", //这个有可能是数组
     * "adcode":"440106",
     * "township":"石牌街道",
     * "neighborhood":{"name":"芳草园","type":"商务住宅;住宅区;住宅小区"},
     * "building":{"name":[],"type":[]},
     * "streetNumber":{"street":"天河北路","number":"599","location":"113.33878,23.1431331","direction":"东北","distance":"11.1565"},
     * "businessAreas":[{"location":"113.34250465166677,23.13215254916664","name":"石牌","id":"440106"}]
     * */
    HPosition.getCityInf = function(pt,fn){
        this.start();

        if(pt.lng&&pt.lat){
            $.get('?c=source&a=ajax',{
                url:'http://api.zdoz.net/geo2loc_2.aspx',
                data:H.json(pt,'string')
            },function (data) {
                data = H.json(data,'json');
                if(data.status==1){
                    err(data.data);
                    fn(data.data);
                    HPosition.cityInf = data.data;
                }else
                    err(data.info||data);
            });
        }else{
            err('[HPosition.getCityInf]无地点信息');
            stoped||fn&&fn();
        }
    };

    /**
     * 浏览器自带定位
     * 如果定位失败，是没有参数传入回调函数的
     * @param fn function 定位成功后的回调函数，会把coords作为参数传入
     * @param errFn object 处理各种错误的方法。1：用户拒绝定位。2：定位失败。3：定位超时。4：未知错误
     * */
    HPosition.getLocation = function(fn,errFn){
        this.start();
        var thi = HPosition;

        if(navigator.geolocation){
            err('[HPosition.getLocation]正在定位');
            navigator.geolocation.getCurrentPosition(function(position){
                var coords = position.coords;
                coords.lng = coords.longitude;
                coords.lat = coords.latitude;
                thi.position = coords;
                err(coords);
                stoped||fn&&fn(coords);
            },function(e){
                var errcode = 0,
                    myErrMsg = {
                        1:' 已禁止自动定位',
                        2:' 无法定位当前位置',
                        3:' 定位超时',
                        0:' 定位功能发生莫名其妙的错误'
                    };

                switch(e.code){
                    case e.PERMISSION_DENIED:
                        errcode = 1;
                        break;
                    case e.POSITION_UNAVAILABLE:
                        errcode = 2;
                        break;
                    case e.TIMEOUT:
                        errcode = 3;
                }

                if(errFn&&errFn.all)
                    errFn.all(errcode);
                else if(errFn&&errFn[errcode])
                    errFn[errcode](e.message);
                else
                    err(e.message+myErrMsg[errcode]);

            },{timeout:8900});
        }else{
            err('不支持定位');
            return 'false';
        }
    };
    

    /**
     * 停止执行所有回调函数
     * */
    HPosition.stop = function(){
        stoped = true;
    };

    HPosition.start = function(){
        stoped = false;
    };

    window.HPosition = HPosition;

    function err(err) {
        if(debug&&H.verifi.isWeixin()){
            alert(H.json(err,'string'));
        }else 
            console.log(err);
    }
}());

(function(){
    if(!window.H)
        return;
    //把地名中的市，镇，省等字眼去掉
    H.trimPlaceName = function(name){
        return name.replace(/市$|地区$|特别行政区$|区$|省$|镇$|县$/i,'');
    };

    /**
     * 计算两个gps点的距离
     * 出处： http://blog.csdn.net/ztp800201/article/details/44676867
     * lng：经度，lat：纬度
     * @param aLat number 第一个和第二个参数可以写成对象{lat:133,lng:23}，表示第一个和第二个点的lat+lng
     * @param aLng number 
     * @param bLat number 
     * @param bLng number 
     * @return number 单位为千米
     * */
    H.getDistance = function(aLat,aLng,bLat,bLng){
        var EARTH_RADIUS = 6378.137;//地球半径，单位千米

        if(typeof aLat=='object'){
            bLat = aLng.lat;
            bLng = aLng.lng;
            aLng = aLat.lng;
            aLat = aLat.lat;
        }
        if(!(aLat&&aLng&&bLat&&bLng)){
            console.error('[H.getDistance]参数不足');
            return 0;
        }

        function rad(d){
            return d * Math.PI / 180.0;
        }

        function distance(lat1, lng1, lat2, lng2){
            var radLat1 = rad(lat1);
            var radLat2 = rad(lat2);
            var a = radLat1 - radLat2;
            var b = rad(lng1) - rad(lng2);
            var s = EARTH_RADIUS * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));

            s = Math.round(s * 10000) / 10000;
            return s;
        }

        return distance(aLat,aLng,bLat,bLng);
    };
    
}());